<template>
  <div class="search-container">
    <div class="goodsSearch">
      <div class="title">
        <span class="home">搜索 > </span
        ><span class="keyword">{{ searchVal }}</span>
      </div>
      <div class="products-grid acea-row" v-if="productslist.length">
        <ProductCard
          v-for="(item, index) in productslist"
          :key="index"
          :product="item"
          @click="goDetail(item)"
        />
      </div>
      <div
        class="loadingicon acea-row row-center-wrapper"
        v-if="productslist.length && productslist.length >= limit"
      >
        <span class="loading iconfont icon-jiazai" v-if="!pullRefreshss"></span
        >{{ title }}
      </div>
      <div class="noCart" v-if="!productslist.length">
        <div class="pictrue"><img src="../assets/images/noCart.png" /></div>
        <div class="tip">抱歉，没有找到您搜索的相关商品~</div>
      </div>
      <hotGoods v-if="!productslist.length"></hotGoods>
    </div>
  </div>
</template>

<script>
import hotGoods from "@/components/hotGoods";
import ProductCard from "@/components/ProductCard";
export default {
  name: "goods_search",
  auth: false,
  components: {
    hotGoods,
    ProductCard,
  },
  // 添加路由导航守卫
  beforeRouteEnter(to, from, next) {
    console.log("搜索页面路由守卫，参数:", to.query);
    // 不再重定向到首页，即使没有搜索关键词
    next();
  },
  data() {
    return {
      headerList: [
        {
          name: "首頁",
          url: "/",
        },
        {
          name: "產品分類",
          url: "/goods_cate",
        },
        {
          name: "限時秒殺",
          url: "/goods_seckill",
        },
        {
          name: "限时预售",
          url: "/goods_presell",
        },
        {
          name: "領優惠券",
          url: "/user/userCoupon?page_type=6",
        },
      ],
      searchVal: "",
      productslist: [],
      pullRefreshss: true, // 代表可以进行下拉加載，false代表不能
      page: 1, //代表页面的初始页数
      limit: 20,
      scollY: null, // 离底部距离有多少
      pageTotal: 50, //總页数
      title: "下拉加載更多",
    };
  },
  async asyncData({ $axios }) {
    // const keyCode = await $axios.$get('/verify_code')
    // return { keyCode:keyCode.key }
  },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: "商品搜索-" + this.$store.state.titleCon,
    };
  },
  created() {
    console.log("搜索页面created钩子执行，路由参数:", this.$route.query);
    this.searchVal = this.$route.query.title || "";
    console.log("设置搜索值:", this.searchVal);

    // 即使没有搜索关键词也不跳转，只显示提示
    if (!this.searchVal) {
      console.warn("搜索关键词为空，显示提示");
      this.$nextTick(() => {
        this.$message.warning("请输入搜索关键词");
      });
      // 不返回，继续执行，但不请求数据
    } else {
      // 有搜索关键词时才请求数据
      this.getProductslist();
    }
  },
  mounted() {
    this.pullRefresh();
  },
  watch: {
    // 监听路由参数变化，当在搜索页面内再次搜索时重新获取数据
    "$route.query": {
      handler(newQuery, oldQuery) {
        console.log("路由参数变化:", newQuery, oldQuery);
        // 更新搜索关键词
        this.searchVal = newQuery.title || "";

        // 重置分页和数据
        this.page = 1;
        this.productslist = [];
        this.pullRefreshss = true;
        this.title = "下拉加載更多";

        // 如果有搜索关键词则重新获取数据
        if (this.searchVal) {
          this.getProductslist();
        } else {
          this.$message.warning("请输入搜索关键词");
        }
      },
      deep: true,
      immediate: false, // 不立即执行，避免与created重复
    },
  },
  beforeDestroy() {
    window.onscroll = null;
  },
  methods: {
    goHome() {
      this.$router.push({ path: "/" });
    },
    goDetail(item) {
      let path = item.presale
        ? (path = {
            path: "/goods_presell_detail",
            query: {
              id: item.id,
            },
          })
        : (path = { path: `/goods_detail/${item.id}` });
      this.$router.push(path);
    },
    search() {
      console.log("执行搜索方法，搜索值:", this.searchVal);
      if (this.searchVal.trim() !== "") {
        this.productslist = [];
        this.pullRefreshss = true;
        this.page = 1;
        this.getProductslist();
      } else {
        this.$message.error("請輸入要搜索的類容");
      }
    },
    getProductslist() {
      let _this = this,
        currentPage = {
          page: this.page,
          limit: this.limit,
          keyword: this.searchVal,
        };
      console.log("开始请求搜索数据，关键词:", this.searchVal);

      // 搜索功能不需要检查用户是否已登录
      console.log("搜索功能不检查登录状态");

      // 添加请求头，确保API知道这是搜索页面的请求
      const config = {
        params: currentPage,
        headers: {
          "X-Page-Type": "search_page",
          "X-Skip-Login-Check": "true", // 添加标记，表示不需要登录检查
        },
      };

      _this.$axios
        .get("/pc/get_products", config)
        .then(function (res) {
          console.log("搜索请求成功:", res);
          // 正常处理数据
          _this.pageTotal = res.data ? res.data.count : 0;
          // 请求完成后，把得到的數據拼接到当前dom里面
          if (res.data && res.data.list) {
            _this.productslist = _this.productslist.concat(res.data.list);
          } else {
            console.warn("搜索结果数据格式不正确或为空");
          }
        })
        .catch(function (err) {
          console.error("搜索请求失败:", err);
          // 显示错误提示而不是跳转
          _this.$message.error("搜索请求失败，请稍后重试");
        });
    },
    // 下拉加載ajax
    pullRefresh: function () {
      var _this = this;
      window.onscroll = function () {
        _this.scrollChange();
      };
    },
    scrollChange: function () {
      let _this = this;
      this.scollY =
        this.comsys.getScrollTop() +
        this.comsys.getWindowHeight() -
        this.comsys.getScrollHeight();
      // 把下拉刷新置為false，防止多次请求
      if (this.scollY >= -50) {
        if (this.page > Math.ceil(this.pageTotal / this.limit)) {
          this.title = "已没有更多數據";
          this.pullRefreshss = true;
          return false;
        }
        if (!this.pullRefreshss) {
          return false;
        }
        _this.pullRefreshss = false;
        _this.title = "正在加載中....";
        // 加页碼数
        this.page++;
        _this.getProductslist();
      } else {
        // 其他时候把下拉刷新置為true
        _this.pullRefreshss = true;
        this.title = "下拉加載更多";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.search-container {
  padding: 0 min(160px, 8vw);
  margin: 0 auto;
  padding-top: 100px;
}

.goodsSearch {
  .title {
    height: 60px;
    line-height: 60px;
    color: $ivory;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    margin-bottom: 40px;
    font-size: 18px;

    .home {
      color: $pure-white;
    }
  }

  // 商品網格佈局
  .products-grid {
    &.acea-row {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 3rem 1.5rem;
      align-items: start;
      margin-bottom: 20px;
    }
  }

  .noCart {
    text-align: center;
    margin-bottom: 70px;

    .pictrue {
      width: 216px;
      height: 136px;
      margin: 0 auto;

      img {
        width: 100%;
        height: 100%;
      }

      .tip {
        margin-top: 12px;
        color: $charcoal;
      }
    }
  }
}
</style>
